<template>
  <div>
    <el-form label-width="70px">
      <el-form-item label="SKU名称">
        <el-input placeholder="请输入SKU名称" v-model="skuParams.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input
          placeholder="请输入价格"
          type="number"
          v-model="skuParams.price"
        />
      </el-form-item>
      <el-form-item label="重量(克)">
        <el-input
          placeholder="请输入重量"
          type="number"
          v-model="skuParams.weight"
        />
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input
          placeholder="请输入SKU描述"
          type="textarea"
          v-model="skuParams.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form class="el_form_attr" inline>
          <el-form-item
            v-for="item in attrArr"
            :key="item.id"
            :label="item.attrName"
          >
            <el-select placeholder="请选择" v-model="item.attrIdAndValueId">
              <el-option
                v-for="attrValue in item.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${item.id}:${attrValue.id}`"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form class="el_form_attr" inline>
          <el-form-item
            v-for="item in saleArr"
            :key="item.id"
            :label="item.saleAttrName"
          >
            <el-select placeholder="请选择" v-model="item.saleIdAndValueId">
              <el-option
                v-for="saleAttrValue in item.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                :label="saleAttrValue.saleAttrValueName"
                :value="`${item.id}:${saleAttrValue.id}`"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table border stripe :data="imgArr" ref="table">
          <el-table-column type="selection" align="center" width="100" />
          <el-table-column label="图片" align="center">
            <template #default="{ row }">
              <el-image :src="row.imgUrl" style="width: 100px; height: 100px" />
            </template>
          </el-table-column>
          <el-table-column label="名称" align="center" prop="imgName" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column label="更新时间" align="center" prop="updateTime" />
          <el-table-column label="操作" align="center" width="200">
            <template #default="{ row }">
              <el-button type="warning" @click="handler(row)">
                设为默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="info" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import type {
  SkuData,
  SpuData,
  SpuImageList,
  SpuSaleAttrListResponseData,
} from '@/api/product/spu/type'
// 引入请求API
import { reqGetAttrList } from '@/api/product/attr'
import {
  reqSpuImageList,
  reqSpuSaleAttrList,
  reqAddSku,
} from '@/api/product/spu'
import type { AttrResponseData } from '@/api/product/attr/type'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

// 平台属性
let attrArr = ref<any>([])
// 照片墙数据
let imgArr = ref<any>([])
// 销售属性
let saleArr = ref<any>([])
// 收集 SKU 数据
let skuParams = reactive<SkuData>({
  // 通过父组件传递过来的数据收集
  category3Id: '',
  spuId: '',
  tmId: '',
  // 通过 v-model 收集
  skuName: '',
  price: '',
  weight: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: '',
})
// 获取 table 组件实例
let table = ref<any>()

// 当前子组件的方法对外暴露
const initSkuData = async (
  category1Id: number | string,
  category2Id: number | string,
  spu: SpuData,
) => {
  // 收集数据
  skuParams.category3Id = spu.category3Id
  skuParams.spuId = spu.id as number
  skuParams.tmId = spu.tmId
  // 获取平台属性
  let attrList: AttrResponseData = await reqGetAttrList(
    category1Id,
    category2Id,
    spu.category3Id,
  )
  // 获取照片墙数据
  let imageList: SpuImageList = await reqSpuImageList(spu.id as number)
  // 获取销售属性
  let spuSaleAttrList: SpuSaleAttrListResponseData = await reqSpuSaleAttrList(
    spu.id as number,
  )
  // 存储数据
  attrArr.value = attrList.data
  imgArr.value = imageList.data
  saleArr.value = spuSaleAttrList.data
}

// 保存按钮
const save = async () => {
  // 整理参数
  skuParams.skuAttrValueList = attrArr.value.reduce((prev: any, next: any) => {
    if (next.attrIdAndValueId) {
      let [attrId, valueId] = next.attrIdAndValueId.split(':')
      prev.push({ attrId, valueId })
    }
    return prev
  }, [])
  skuParams.skuSaleAttrValueList = saleArr.value.reduce(
    (prev: any, next: any) => {
      if (next.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':')
        prev.push({ saleAttrId, saleAttrValueId })
      }
      return prev
    },
    [],
  )
  // 发送请求
  let result = await reqAddSku(skuParams)
  if (result.code === 200) {
    ElMessage.success('保存成功')
  } else {
    ElMessage.error('保存失败')
  }
  // 通知父组件切换场景
  $emit('changeScene', { flag: 0, params: 'update' })
}

// 自定义事件
let $emit = defineEmits(['changeScene'])

// 取消按钮
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}

// 设置默认图片的回调
const handler = (row: any) => {
  // 每次点击的时候，先让全部的复选框不勾选
  imgArr.value.forEach((item: any) => {
    table.value.toggleRowSelection(item, false)
  })
  // 只有选中的图片复选框选才勾选
  table.value.toggleRowSelection(row, true)
  skuParams.skuDefaultImg = row.imgUrl
}

defineExpose({ initSkuData })
</script>

<style scoped>
.el_form_attr .el-form-item .el-select {
  width: 300px;
  margin-bottom: 10px;
}
</style>
